<template>
  <div class="dashboard">
    <!-- Page Header -->
    <div class="page-header">
      <div>
        <h1 class="page-title">Dashboard</h1>
        <p class="page-subtitle">Real-time Monitoring & System Overview · Last updated: {{ currentTime }}</p>
      </div>
      <a-space>
        <a-button @click="refreshData">
          <template #icon><ReloadOutlined :spin="loading" /></template>
          Refresh
        </a-button>
        <a-range-picker v-model:value="dateRange" style="width: 280px" />
      </a-space>
    </div>

    <!-- Statistics Cards -->
    <a-row :gutter="[16, 16]" class="mb-6">
      <a-col :xs="24" :sm="12" :lg="6" v-for="stat in stats" :key="stat.title">
        <div class="stat-card" :class="`stat-card-${stat.type}`">
          <div class="stat-card-inner">
            <div class="stat-icon" :style="{ background: stat.gradient }">
              <component :is="stat.icon" />
            </div>
            <div class="stat-content">
              <div class="stat-value">
                <a-statistic
                  :value="stat.value"
                  :precision="0"
                  :value-style="{ color: stat.color, fontSize: '24px', fontWeight: 600 }"
                >
                  <template #suffix v-if="stat.suffix">
                    <span style="font-size: 14px; color: #8c8c8c">{{ stat.suffix }}</span>
                  </template>
                </a-statistic>
              </div>
              <div class="stat-title">{{ stat.title }}</div>
              <div class="stat-trend" v-if="stat.trend">
                <a-tag :color="stat.trend > 0 ? 'success' : 'error'" class="trend-tag">
                  <template #icon>
                    <ArrowUpOutlined v-if="stat.trend > 0" />
                    <ArrowDownOutlined v-else />
                  </template>
                  {{ Math.abs(stat.trend) }}%
                </a-tag>
                <span class="trend-text">vs yesterday</span>
              </div>
            </div>
          </div>
          <div class="stat-sparkline">
            <div class="sparkline" :style="{ background: `linear-gradient(90deg, ${stat.gradient})` }" />
          </div>
        </div>
      </a-col>
    </a-row>

    <!-- System Status -->
    <a-row :gutter="[16, 16]">
      <a-col :xs="24" :lg="12">
        <a-card title="Recent Alerts" :bordered="false" class="chart-card alerts-card">
          <template #extra>
            <a href="#" @click.prevent="router.push('/alerts')">
              <small>View All</small>
            </a>
          </template>
          <a-list size="small" :data-source="recentAlerts">
            <template #renderItem="{ item }">
              <a-list-item class="alert-item">
                <a-list-item-meta>
                  <template #avatar>
                    <a-badge :status="getStatusBadge(item.severity)" />
                  </template>
                  <template #title>
                    <div class="alert-title">{{ item.title }}</div>
                  </template>
                  <template #description>
                    <div class="alert-meta">
                      <ClockCircleOutlined class="meta-icon" />
                      {{ item.time }}
                    </div>
                  </template>
                </a-list-item-meta>
              </a-list-item>
            </template>
          </a-list>
        </a-card>
      </a-col>

      <a-col :xs="24" :lg="12">
        <a-card title="Service Health Status" :bordered="false" class="chart-card">
          <div class="services-grid">
            <div
              v-for="service in services"
              :key="service.name"
              class="service-item"
              :class="`service-${service.status}`"
            >
              <div class="service-icon">
                <component :is="service.icon" />
              </div>
              <div class="service-info">
                <div class="service-name">{{ service.name }}</div>
                <div class="service-status">
                  <a-badge :status="service.status === 'healthy' ? 'success' : 'error'" />
                  {{ service.status === 'healthy' ? 'Running' : 'Error' }}
                </div>
              </div>
              <div class="service-metrics">
                <div class="metric">
                  <small>Response Time</small>
                  <strong>{{ service.responseTime }}ms</strong>
                </div>
              </div>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import type { ECharts } from 'echarts'
import dayjs from 'dayjs'
import {
  ReloadOutlined,
  ThunderboltOutlined,
  BellOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  DatabaseOutlined,
  CloudOutlined,
  ApiOutlined,
  DashboardOutlined,
  FileTextOutlined,
} from '@ant-design/icons-vue'

const router = useRouter()
const loading = ref(false)
const chartRef = ref<HTMLElement>()
const chartPeriod = ref('6h')
const dateRange = ref()
const currentTime = ref(dayjs().format('HH:mm:ss'))

let chart: ECharts | null = null
let timeInterval: any = null

const stats = ref([
  {
    title: 'Total Systems',
    value: 156,
    suffix: '',
    color: '#52c41a',
    type: 'primary',
    gradient: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    icon: DashboardOutlined,
    trend: 12,
  },
  {
    title: 'Active Alerts',
    value: 23,
    suffix: '',
    color: '#ff4d4f',
    type: 'danger',
    gradient: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
    icon: BellOutlined,
    trend: -5,
  },
  {
    title: 'Resolution Rate',
    value: 89,
    suffix: '%',
    color: '#1890ff',
    type: 'info',
    gradient: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
    icon: CheckCircleOutlined,
    trend: 8,
  },
  {
    title: 'Avg Response',
    value: 12,
    suffix: 'min',
    color: '#722ed1',
    type: 'warning',
    gradient: 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
    icon: ClockCircleOutlined,
    trend: -15,
  },
])

const recentAlerts = ref([
  { title: 'High CPU Usage - server-01', severity: 'error', time: '5 minutes ago' },
  { title: 'Memory Usage Alert - server-02', severity: 'warning', time: '10 minutes ago' },
  { title: 'Low Disk Space - server-03', severity: 'error', time: '30 minutes ago' },
  { title: 'Network Latency Increase - gateway-01', severity: 'warning', time: '1 hour ago' },
  { title: 'API Response Time Increase', severity: 'warning', time: '2 hours ago' },
])

const services = ref([
  { name: 'MongoDB', icon: DatabaseOutlined, status: 'healthy', responseTime: 45 },
  { name: 'Redis', icon: DatabaseOutlined, status: 'healthy', responseTime: 12 },
  { name: 'API Gateway', icon: ApiOutlined, status: 'healthy', responseTime: 89 },
  { name: 'Prometheus', icon: CloudOutlined, status: 'healthy', responseTime: 156 },
])

// Removed performanceMetrics - was mock data

const getStatusBadge = (severity: string) => {
  const map: Record<string, any> = {
    error: 'error',
    warning: 'warning',
    success: 'success',
  }
  return map[severity] || 'default'
}

const initChart = () => {
  if (!chartRef.value) return

  chart = echarts.init(chartRef.value)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
      },
    },
    legend: {
      data: ['CPU', 'Memory', 'Network'],
      bottom: 0,
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: Array.from({ length: 24 }, (_, i) => `${i}:00`),
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value}%',
      },
    },
    series: [
      {
        name: 'CPU',
        type: 'line',
        smooth: true,
        areaStyle: {
          opacity: 0.3,
        },
        data: Array.from({ length: 24 }, () => Math.floor(Math.random() * 60 + 20)),
        itemStyle: {
          color: '#667eea',
        },
      },
      {
        name: 'Memory',
        type: 'line',
        smooth: true,
        areaStyle: {
          opacity: 0.3,
        },
        data: Array.from({ length: 24 }, () => Math.floor(Math.random() * 50 + 30)),
        itemStyle: {
          color: '#4facfe',
        },
      },
      {
        name: 'Network',
        type: 'line',
        smooth: true,
        areaStyle: {
          opacity: 0.3,
        },
        data: Array.from({ length: 24 }, () => Math.floor(Math.random() * 70 + 10)),
        itemStyle: {
          color: '#f5576c',
        },
      },
    ],
  }

  chart.setOption(option)

  // Responsive
  window.addEventListener('resize', () => {
    chart?.resize()
  })
}

const loadDashboardData = async () => {
  try {
    const { getDashboardOverview, getRecentAlerts, getServicesStatus, getPerformanceMetrics } = await import('@/api/dashboard')

    const [overviewRes, alertsRes, servicesRes, metricsRes] = await Promise.all([
      getDashboardOverview(),
      getRecentAlerts(5),
      getServicesStatus(),
      getPerformanceMetrics(24)
    ])

    if (overviewRes.data?.stats) {
      stats.value = overviewRes.data.stats.map(stat => ({
        ...stat,
        icon: stat.type === 'success' ? FileTextOutlined :
              stat.type === 'danger' ? BellOutlined :
              stat.type === 'info' ? CheckCircleOutlined :
              ClockCircleOutlined
      }))
    }

    if (alertsRes.data) {
      recentAlerts.value = alertsRes.data
    }

    if (servicesRes.data) {
      services.value = servicesRes.data.map(service => ({
        ...service,
        icon: service.name.includes('MongoDB') || service.name.includes('Redis') ? DatabaseOutlined :
              service.name.includes('API') ? ApiOutlined :
              CloudOutlined
      }))
    }

    // Removed performance metrics handling - was mock data
  } catch (error) {
    console.error('Failed to load dashboard data:', error)
  }
}

const refreshData = async () => {
  loading.value = true
  try {
    await loadDashboardData()
    currentTime.value = dayjs().format('HH:mm:ss')
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  await loadDashboardData()

  // Update time every second
  timeInterval = setInterval(() => {
    currentTime.value = dayjs().format('HH:mm:ss')
  }, 1000)
})

onUnmounted(() => {
  if (timeInterval) {
    clearInterval(timeInterval)
  }
})
</script>

<style scoped>
.dashboard {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 20px 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.03);
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.page-subtitle {
  margin: 4px 0 0;
  font-size: 14px;
  color: #6b7280;
}

.stat-card {
  position: relative;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 24px -8px rgba(0, 0, 0, 0.15);
}

.stat-card-inner {
  position: relative;
  z-index: 1;
  display: flex;
  gap: 16px;
}

.stat-icon {
  width: 56px;
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12px;
  font-size: 24px;
  color: white;
  flex-shrink: 0;
}

.stat-content {
  flex: 1;
  min-width: 0;
}

.stat-value {
  margin-bottom: 4px;
}

.stat-title {
  font-size: 14px;
  color: #6b7280;
  margin-bottom: 8px;
}

.stat-trend {
  display: flex;
  align-items: center;
  gap: 8px;
}

.trend-tag {
  font-size: 12px;
  font-weight: 500;
}

.trend-text {
  font-size: 12px;
  color: #9ca3af;
}

.stat-sparkline {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 3px;
  opacity: 0.3;
}

.sparkline {
  height: 100%;
  width: 100%;
}

.chart-card {
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  border-radius: 12px;
}

.chart-card :deep(.ant-card-head) {
  border-bottom: 1px solid #f0f0f0;
  padding: 16px 24px;
}

.chart-card :deep(.ant-card-body) {
  padding: 24px;
}

.chart-container {
  height: 350px;
}

.alerts-card :deep(.ant-list-item) {
  padding: 12px 0;
  transition: all 0.2s ease;
  border-radius: 8px;
  margin: 0 -8px;
  padding-left: 8px;
  padding-right: 8px;
}

.alerts-card :deep(.ant-list-item:hover) {
  background: #f9fafb;
}

.alert-item {
  cursor: pointer;
}

.alert-title {
  font-size: 14px;
  color: #1f2937;
  margin-bottom: 4px;
}

.alert-meta {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #9ca3af;
}

.meta-icon {
  font-size: 12px;
}

.services-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.service-item {
  padding: 16px;
  background: #f9fafb;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 12px;
  transition: all 0.2s ease;
}

.service-item:hover {
  background: #f3f4f6;
  transform: translateY(-2px);
}

.service-icon {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  border-radius: 8px;
  font-size: 20px;
  color: #667eea;
}

.service-info {
  flex: 1;
  min-width: 0;
}

.service-name {
  font-size: 14px;
  font-weight: 500;
  color: #1f2937;
  margin-bottom: 4px;
}

.service-status {
  font-size: 12px;
  color: #6b7280;
  display: flex;
  align-items: center;
  gap: 4px;
}

.service-metrics {
  text-align: right;
}

.metric small {
  display: block;
  font-size: 11px;
  color: #9ca3af;
  margin-bottom: 2px;
}

.metric strong {
  display: block;
  font-size: 13px;
  color: #1f2937;
}

.performance-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.performance-item {
  padding: 16px;
  background: #f9fafb;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 12px;
  transition: all 0.2s ease;
}

.performance-item:hover {
  background: #f3f4f6;
  transform: translateY(-2px);
}

.performance-info {
  flex: 1;
  min-width: 0;
}

.performance-name {
  font-size: 14px;
  font-weight: 500;
  color: #1f2937;
  margin-bottom: 2px;
}

.performance-value {
  font-size: 16px;
  font-weight: 700;
  color: #667eea;
}

.performance-progress-wrapper {
  flex: 1;
  min-width: 80px;
  max-width: 120px;
}

.performance-progress-wrapper :deep(.ant-progress-line) {
  margin: 0;
  padding: 0;
}

.performance-progress-wrapper :deep(.ant-progress-outer) {
  margin: 0;
  padding: 0;
}

.mb-6 {
  margin-bottom: 24px;
}

.mb-4 {
  margin-bottom: 16px;
}
</style>
